<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>银行综合服务系统</title>
    <style>
        /* 样式部分保持不变，参考用户提供的原始CSS */
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Segoe UI', sans-serif; background-color: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        nav { background-color: #007BFF; padding: 1rem; margin-bottom: 2rem; border-radius: 5px; }
        nav ul { display: flex; list-style: none; gap: 2rem; }
        nav a { color: white; text-decoration: none; padding: 0.5rem 1rem; border-radius: 3px; transition: background-color 0.3s; }
        nav a:hover { background-color: #0056b3; }
        .page { display: none; background: white; padding: 2rem; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .active { display: block; }
        h2 { color: #333; margin-bottom: 1.5rem; }
        form { max-width: 500px; margin: 0 auto; }
        .form-group { margin-bottom: 1rem; }
        label { display: block; margin-bottom: 0.5rem; color: #666; }
        input, select { width: 100%; padding: 0.8rem; border: 1px solid #ddd; border-radius: 4px; font-size: 1rem; }
        button { background-color: #28a745; color: white; padding: 0.8rem 1.5rem; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; transition: background-color 0.3s; }
        button:hover { background-color: #218838; }
        .balance { font-size: 2rem; color: #28a745; text-align: center; margin: 2rem 0; }
        .transaction-item { padding: 0.5rem; border-bottom: 1px solid #eee; }
    </style>
</head>
<body>
<div class="container">
    <nav>
        <ul>
            <li><a href="#home" onclick="showPage('home')">主页</a></li>
            <li><a href="#account" onclick="showPage('account')">账户概览</a></li>
            <li><a href="#deposit" onclick="showPage('deposit')">存款</a></li>
            <li><a href="#withdraw" onclick="showPage('withdraw')">取款</a></li>
            <li><a href="#" onclick="logout()">退出</a></li>
        </ul>
    </nav>

    <!-- 主页 -->
    <div id="home" class="page active">
        <h2>欢迎使用银行综合服务系统</h2>
        <p>请通过上方菜单选择需要的服务</p>
    </div>

    <!-- 账户概览 -->
    <div id="account" class="page">
        <h2>账户概览</h2>
        <div class="balance">
            当前余额：¥ <span id="currentBalance">加载中...</span>
        </div>
        <h3>最近交易记录</h3>
        <ul id="transactionList">
            <li class="transaction-item">正在加载交易记录...</li>
        </ul>
    </div>

    <!-- 存款 -->
    <div id="deposit" class="page">
        <h2>存款操作</h2>
        <form id="depositForm">
            <div class="form-group">
                <label for="depositAmount">存款金额（元）:</label>
                <input type="number" id="depositAmount" step="0.01" min="0.01" required>
            </div>
            <button type="submit">立即存款</button>
        </form>
    </div>

    <!-- 取款 -->
    <div id="withdraw" class="page">
        <h2>取款操作</h2>
        <form id="withdrawForm">
            <div class="form-group">
                <label for="withdrawAmount">取款金额（元）:</label>
                <input type="number" id="withdrawAmount" step="0.01" min="0.01" required>
            </div>
            <button type="submit">立即取款</button>
        </form>
    </div>
</div>

<script>
    let currentUser = sessionStorage.getItem('currentUser');
    if (!currentUser) {
        window.location.href = 'login.html';
    }

    // 显示页面并修改 URL
    function showPage(pageId) {
        document.querySelectorAll('.page').forEach(page => {
            page.classList.remove('active');
        });
        document.getElementById(pageId).classList.add('active');
        window.location.hash = pageId;  // 更新 URL Hash
    }

    // 根据 URL Hash 跳转
    window.addEventListener('load', handleHashChange);
    window.addEventListener('hashchange', handleHashChange);

    function handleHashChange() {
        const pageId = location.hash.replace('#', '') || 'home';
        showPage(pageId);
    }

    // 加载账户数据
    async function loadAccountData() {
        try {
            const userRes = await fetch(`/api/user/${currentUser}`);
            const userData = await userRes.json();
            document.getElementById('currentBalance').textContent = userData.amount.toFixed(2);

            const txRes = await fetch(`/api/transactions/${currentUser}`);
            const transactions = await txRes.json();
            const txList = document.getElementById('transactionList');
            txList.innerHTML = transactions.map(tx => `
                <li class="transaction-item">
                    [${new Date(tx.timestamp).toLocaleString()}]
                    ${tx.type}
                    ${tx.amount > 0 ? '+' : ''}${tx.amount.toFixed(2)}元
                    <button onclick="deleteTransaction('${tx.id}')">删除</button>
                </li>
            `).join('');
        } catch (error) {
            console.error('数据加载失败:', error);
            alert('系统繁忙，请稍后重试！');
        }
    }
    function logout() {
        if (confirm("确定要退出登录吗？")) {
            sessionStorage.removeItem('currentUser');
            window.location.href = 'login.html';
        }
    }
    async function deleteTransaction(id) {
        if (!confirm('确定要删除这条交易记录吗？')) return;

        const btn = event.target;
        btn.disabled = true;
        btn.textContent = '删除中...';

        try {
            const response = await fetch(`/api/transactions/${id}`, { method: 'DELETE' });
            const result = await response.json();

            if (response.ok) {
                alert(result.message || '交易记录已删除');
                await loadAccountData();
            } else {
                alert('删除失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            alert('网络错误，删除失败');
        } finally {
            btn.disabled = false;
            btn.textContent = '删除';
        }
    }


    async function deleteSelectedTransactions() {
        const selected = Array.from(document.querySelectorAll('.tx-checkbox:checked'));
        if (selected.length === 0) return alert('请选择要删除的记录');
        if (!confirm(`确定删除选中的 ${selected.length} 条记录吗？`)) return;

        let failed = 0;

        for (let i = 0; i < selected.length; i++) {
            const checkbox = selected[i];
            const response = await fetch(`/api/transactions/${checkbox.value}`, { method: 'DELETE' });
            const result = await response.json();

            if (!response.ok) {
                failed++;
                alert(`❌ 第 ${i + 1} 条失败: ${result.message || '未知错误'}`);
            } else {
                console.log(`✅ 第 ${i + 1} 条已删除`);
            }
        }

        alert(`处理完成。共 ${selected.length} 条，成功 ${selected.length - failed} 条，失败 ${failed} 条。`);
        await loadAccountData();
    }


    document.getElementById('depositForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const amount = parseFloat(document.getElementById('depositAmount').value);
        try {
            const response = await fetch('/api/user/deposit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ number: currentUser, amount: amount })
            });
            const result = await response.json();
            if (result.success) {
                alert(`成功存入 ${amount.toFixed(2)}元！`);
                await loadAccountData();
            } else {
                alert('操作失败: ' + (result.message || '系统错误'));
            }
        } catch (error) {
            alert('网络连接异常！');
        }
    });

    document.getElementById('withdrawForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const amount = parseFloat(document.getElementById('withdrawAmount').value);
        try {
            const response = await fetch('/api/user/withdraw', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ number: currentUser, amount: amount })
            });
            const result = await response.json();
            if (result.success) {
                alert(`成功取出 ${amount.toFixed(2)}元！`);
                await loadAccountData();
            } else {
                alert('操作失败: ' + (result.message || '余额不足或系统错误'));
            }
        } catch (error) {
            alert('网络连接异常！');
        }
    });

    window.onload = () => {
        loadAccountData();
        setInterval(loadAccountData, 30000);
    };
</script>
</body>
</html>


